package com.wangyan.javabean2doc.ui;

import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.ActionToolbarPosition;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.TableUtil;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.TableView;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.wangyan.javabean2doc.ExcelAdapter;
import com.wangyan.javabean2doc.RowData;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.util.List;

/**
 * @author wangyan
 * @date 2024/01/26/14:20
 * @description
 */
public class TableUI {

    private JPanel jPanel;
    @Getter
    private JPanel root;

    private TableView<RowData> tableView;
    private ExcelAdapter myAd;

    ListTableModel<RowData> model = new ListTableModel<>(
            new MybaitsxModuleInfo("字段名称"),
            new MybaitsxModuleInfo("字段含义"),
            new MybaitsxModuleInfo("数据类型"),
            new MybaitsxModuleInfo("是否必须"),
            new MybaitsxModuleInfo("备注")
    );

    public void fillData(Project project, List<RowData> rowDataList) {

        tableView = new TableView<>(model);
        tableView.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
        myAd = new ExcelAdapter(tableView);

        GridConstraints gridConstraints = new GridConstraints();
        gridConstraints.setFill(GridConstraints.FILL_HORIZONTAL);

        jPanel.add(ToolbarDecorator.createDecorator(tableView)
                .setToolbarPosition(ActionToolbarPosition.LEFT)
                .setAddAction(a -> {
                    model.addRow(new RowData());
                })
                .addExtraAction(
                        new ToolbarDecorator.ElementActionButton(IdeBundle.message("button.copy"), PlatformIcons.COPY_ICON) {
                            @Override
                            public void actionPerformed(@NotNull AnActionEvent e) {
                                TableUtil.stopEditing(tableView);

                                List<RowData> selectedItems = tableView.getSelectedObjects();
                                if (selectedItems.isEmpty()) {
                                    return;
                                }

                                for (RowData item : selectedItems) {
                                    RowData.builder()
                                            .desc(item.getDesc())
                                            .name(item.getName())
                                            .required(item.getRequired())
                                            .type(item.getType())
                                            .filed(item.getFiled())
                                            .build();
                                    model.addRow(item);
                                }

                                IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(tableView, true));
                                TableUtil.updateScroller(tableView);
                            }
                        }
                )
                .setPreferredSize(new Dimension(860, 500))
                .createPanel(), gridConstraints);
        for (RowData rowData : rowDataList) {
            model.addRow(rowData);
        }


    }

    public void copy() {
        myAd.generateHtmlTable();
    }

    public void copy1() {
        int rowCount = tableView.getRowCount();
        int columnCount = tableView.getColumnCount();
        int[] rowArray = new int[rowCount];
        int[] columnArray = new int[columnCount];
        for (int i = 0; i < rowCount; i++) {
            rowArray[i] = i;
        }
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < columnCount; i++) {
            columnArray[i] = i;
            sb.append(tableView.getColumnName(i));
            if (i != columnCount - 1) {
                sb.append("\t");
            }

        }

        myAd.copy(columnCount, rowCount, rowArray, columnArray, sb.toString());
    }

    private class MybaitsxModuleInfo extends ColumnInfo<RowData, String> {

        public MybaitsxModuleInfo(String name) {
            super(name);
        }

        @Override
        public boolean isCellEditable(RowData rowData) {
            return true;
        }

        @Nullable
        @Override
        public TableCellRenderer getRenderer(RowData rowData) {
            return new DefaultTableCellRenderer();
        }


        @Nullable
        @Override
        public TableCellEditor getEditor(RowData rowData) {
            JTextField textField = new JTextField();

            DefaultCellEditor defaultCellEditor = new DefaultCellEditor(textField);
            defaultCellEditor.addCellEditorListener(new CellEditorListener() {
                @Override
                public void editingStopped(ChangeEvent e) {
                    String s = defaultCellEditor.getCellEditorValue().toString();
                    if (getName().equals("字段名称")) {
                        rowData.setFiled(s);
                    } else if (getName().equals("字段含义")) {
                        rowData.setName(s);
                    } else if (getName().equals("数据类型")) {
                        rowData.setType(s);
                    } else if (getName().equals("是否必须")) {
                        rowData.setRequired(s);
                    } else if (getName().equals("备注")) {
                        rowData.setDesc(s);
                    }
                }

                @Override
                public void editingCanceled(ChangeEvent e) {

                }
            });
            return defaultCellEditor;
        }

        @Override
        public @Nullable String valueOf(RowData rowData) {
            if (rowData == null) {
                return "";
            }
            String value = null;
            if (getName().equals("字段名称")) {
                value = rowData.getFiled();
            } else if (getName().equals("字段含义")) {
                value = rowData.getName();
            } else if (getName().equals("数据类型")) {
                value = rowData.getType();
            } else if (getName().equals("是否必须")) {
                value = rowData.getRequired();
            } else if (getName().equals("备注")) {
                value = rowData.getDesc();
            }
            return value;
        }
    }
}
